package com.seiko.danmaku.util

import com.seiko.danmaku.data.api.model.DanmaDownloadResponse
import com.seiko.danmaku.data.model.DanmaCommentBean
import org.xml.sax.Attributes
import org.xml.sax.helpers.DefaultHandler

class MySAXParserHandler : DefaultHandler() {
    private var index = 0

    var danmaDownloadResponse = DanmaDownloadResponse()

    var danmaCommentBeanList = ArrayList<DanmaCommentBean>()

    var danmaCommentBean = DanmaCommentBean()

    var trim = ""

    /**
     * 遍历xml的文件开始标签
     */
    override fun startElement(
        uri: String?,
        localName: String?,
        qName: String?,
        attributes: Attributes?
    ) {
        super.startElement(uri, localName, qName, attributes)
        if (qName == "d") {
            danmaCommentBean = DanmaCommentBean()
            danmaCommentBeanList.add(danmaCommentBean)
            index++
            for (i in 0 until attributes!!.length) {
                danmaCommentBean.p = attributes.getValue(i)
            }
        }
    }

    /**
     * 遍历xml文件的结束标签
     */
    override fun endElement(uri: String?, localName: String?, qName: String?) {
        super.endElement(uri, localName, qName)
        when (qName) {
            "d" -> danmaCommentBean.m = trim
        }
    }

    /**
     * 标志解析开始
     */
    override fun startDocument() {
        super.startDocument()
        println("SAX解析开始...")
    }

    /**
     * 标志解析结束
     */
    override fun endDocument() {
        super.endDocument()
        println("SAX解析结束...$index")
        danmaDownloadResponse.count = index
        danmaDownloadResponse.comments = danmaCommentBeanList
    }

    /**
     * 解析内容，获取文本
     */
    override fun characters(ch: CharArray?, start: Int, length: Int) {
        super.characters(ch, start, length)
        val strings = String(ch!!, start, length)
        trim = strings.trim()
    }
}